<?php


namespace SFExpressIsp\Traits;


use SFExpressIsp\Core\ItemInterface;

trait HasItem
{
    protected $objTypes = [];

    protected $data = [];


    public function __construct(array $data = [])
    {
        foreach ($data as $key=>$value){
            if(in_array($key, $this->getObjTypes())){
                if($value instanceof ItemInterface || $value === null){
                    $this->setData($key, $value);
                }else{
                    throw new \InvalidArgumentException(sprintf('%s 参数不正确', $key));
                }
            }else if(array_key_exists($key, $this->getData()) !== false){
                $this->setData($key, $value);
            }
        }
    }

    /**
     * @return array
     * @author luffyzhao@vip.126.com
     */
    protected function getData() :array{
        return $this->data;
    }

    /**
     * @return array
     * @author luffyzhao@vip.126.com
     */
    protected function getObjTypes():array{
        return $this->objTypes;
    }

    /**
     * @param $key
     * @param $value
     * @author luffyzhao@vip.126.com
     */
    protected function setData($key, $value){
        $this->data[$key] = $value;
    }

    /**
     * @param $key
     * @param $value
     * @return bool
     * @author luffyzhao@vip.126.com
     */
    protected function isObjType($key, $value){
        return in_array($key, $this->getObjTypes()) && ($value instanceof ItemInterface || $value === null);
    }
}